package main

import(
	"fmt"
	"net/http"
	"html/template"
	"flag"
	"strconv"
	"golang.org/x/net/websocket"
)

type WsServer struct{
	ListenAddr string
}


//唯一id
var uid = 1
//客户端客户端
var clientList = make(map[int]Client)
var hall = &Hall{C:make(chan string)}

func (this *WsServer) wsHandler(conn *websocket.Conn) {
	defer conn.Close()
	
	addr := conn.RemoteAddr().String()
	localAddr := conn.LocalAddr().String()
	client := Client{C:make(chan string), SysC:make(chan ClientSysHandler), uid:uid, name:"", addr:addr, localAddr:localAddr, conn:conn, room:0}
	fmt.Println(uid, addr, localAddr)
	go client.start()
	clientList[uid] = client
	client.C <- "你分配到id：" + strconv.Itoa(uid) + ", 请填写你的名字:"
	uid++
	for{
		var reply string
		if err := websocket.Message.Receive(conn, &reply); err != nil{
			fmt.Printf("uid= %d 接收消息错误 %v", client.uid, err.Error())
			break;
		}else{
			if reply == "heartBeat"{
				client.C <- "heartBeat"
			}else if len(reply) >5 && reply[:5] == "name|"{
				oldName := client.name
				client.name = reply[5:]
				clientList[client.uid] = client
				hall.C <- "["+ strconv.Itoa(client.uid) +"]" + "[" + oldName + "]:改名为：" + client.name 
			}else if len(reply) >5 && reply[:5] == "room|"{
				//进入房间
				newId, _ := strconv.Atoi(reply[5:])
				fmt.Println("============", newId)
				RoomChan <- RoomHandler{flag:0, newId:newId, oldId:client.room, uid:client.uid}
			}else if len(reply) >5 && reply[:5] == "quit|"{
				//退出房间
				RoomChan <- RoomHandler{flag:1,  newId:0, oldId:client.room, uid:client.uid}
			}else{
				name := "匿名" + strconv.Itoa(client.uid)
				if client.name != "" {
					name = client.name
				}
				if(client.room == 0){
					hall.C <- "【大厅】" + "[" + name + "]:" + reply
				}else {
					if room, ok := RoomList[client.room]; ok{
						room.C <- "【房间" + strconv.Itoa(client.room) + "】" + "[" + name + "]:" + reply
					}else{
						client.C <- "你所在的房间已经不存在，请先返回大厅"
					}
				}
			}
		}
	}
}

func (this *WsServer) start() (error){
	http.Handle("/ws", websocket.Handler(this.wsHandler))
	fmt.Println("ws begin")
	err := http.ListenAndServe(this.ListenAddr, nil)
	if err != nil{
		fmt.Println("ws ListenAndServe", err)
	}
	return nil
}

func WebHandler(w http.ResponseWriter, r *http.Request){
	t, terr := template.ParseFiles("tpl/index.tpl")
	if terr != nil{
		fmt.Println("加载模板出错", terr)
	}
	t.Execute(w, "Hello world")
	//fmt.Fprintln(w, "hello world")
}


func main() {
	wsaddr := flag.String("a", ":8080", "ws addr")
	flag.Parse()
	http.HandleFunc("/", WebHandler)
	//大厅
	go hall.start()
	go RoomJoin()
	wsServer := &WsServer{
		ListenAddr : *wsaddr,
	}
	fmt.Println("监听8080，开启ws")
	go wsServer.start()
	fmt.Println("监听8000，开启web")
	http.ListenAndServe(":8000", nil)	
	fmt.Println("aaaa")
}